A Silverlight program can display bitmaps in the JPEG and PNG formats with the Image element. Let’s explore the Image element a little more.
The ImageExperiment
project contains a folder named Images containing a file named
BuzzAldrinOnTheMoon.png, which is the famous photograph taken with a
Hasselblad camera by Neil Armstrong on July 21st, 1969. The photo is 288 pixels square.
The file is referenced in the MainPage.xaml file like this:
Example 1. Silverlight Project: ImageExperiment File: MainPage.xaml (excerpt)
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0" Background="{StaticResource PhoneAccentBrush}"> <Image Source="Images/BuzzAldrinOnTheMoon.png" /> </Grid>
|
I’ve also give the content grid a Background brush of the accent color just to make the photo stand out a little better. Here’s how it appears in landscape mode:
By default, the bitmap expands
to the size of its container (the content grid in this case) while
maintaining the correct aspect ratio. Depending on the dimensions and
aspect ratio of the container, the image is centered either horizontally or vertically. You can move it to one side or the other with the HorizontalAlignment and VerticalAlignment properties.
The stretching behavior is governed by a property defined by the Image element named Stretch, which is set to a member of the Stretch enumeration. The default value is Uniform, which you can set explicitly like this:
<Image Source="Images/BuzzAldrinOnTheMoon.png"
Stretch="Uniform" />
The term “uniform” here means equally in both directions so the image is not distorted.
You can also set Stretch to Fill to make the image fill its container by stretching unequally.
A compromise is UniformToFill:
Now the Image
both fills the container and stretches uniformly to preserve the aspect
ratio. How can both goals be accomplished? Well, in general the only
way that can happen is by cropping the image. You can govern which edge
gets cropped with the HorizontalAlignment and VerticalAlignment properties. What setting you use really depends on the particular image.
The fourth option is None for no stretching. Now the image is displayed in its native size of 288 pixels square:
If you want to display the image in a particular size at the correct aspect ratio, you can set either an explicit Width or Height property. If you want to stretch non-uniformly to a particular dimension, specify both Width and Height and set Stretch to Fill.
You can set transforms on the Image element with the same ease that you set them on TextBlock elements:
<Image Source="Images/BuzzAldrinOnTheMoon.png"
RenderTransformOrigin="0.5 0.5">
<Image.RenderTransform>
<RotateTransform Angle="30" />
</Image.RenderTransform>
</Image>
Here it is: